package com.ggb.readingtime.service


import com.ggb.readingtime.properties.JwtProperties
import io.jsonwebtoken.Jwts
import io.jsonwebtoken.SignatureAlgorithm
import lombok.RequiredArgsConstructor
import org.springframework.stereotype.Service
import java.util.Date
@Service
@RequiredArgsConstructor
class JwtService(private val jwtProperties: JwtProperties) {

    /**
     * 生成token
     */
    fun createToken(userId: String): String {
        val claims = Jwts.claims().setSubject(userId)
        val now = Date()
        val validity = Date(now.time + jwtProperties.userTtl)

        return Jwts.builder()
            .setClaims(claims)
            .setIssuedAt(now)
            .setExpiration(validity)
            .signWith(SignatureAlgorithm.HS256, jwtProperties.userSecretKey)
            .compact()
    }

    /**
     * 验证token
     */
    fun validateToken(token: String): Boolean {
        return try {
            Jwts.parser().setSigningKey(jwtProperties.userSecretKey).parseClaimsJws(token).body
            true
        } catch (e: Exception) {
            // Log and handle the exception as per your requirement
            false
        }
    }

    /**
     * 通过token获取userId
     */
    fun getUserIdFromToken(token: String): Int? {
        return try {
            val claims = Jwts.parser().setSigningKey(jwtProperties.userSecretKey).parseClaimsJws(token).body
            claims.subject.toInt()
        } catch (e: Exception) {
            null // 或者处理异常
        }
    }

    /**
     * 生成token
     */
    fun createAuthorizationToken(userId: String): String {
        val claims = Jwts.claims().setSubject(userId)
        val now = Date()
        val validity = Date(now.time + jwtProperties.adminTtl)

        return Jwts.builder()
            .setClaims(claims)
            .setIssuedAt(now)
            .setExpiration(validity)
            .signWith(SignatureAlgorithm.HS256, jwtProperties.adminSecretKey)
            .compact()
    }

    /**
     * 验证后台的token
     */
    fun validateAuthorizationToken(authorizationToken: String): Boolean {
        // 实现验证后台管理令牌的逻辑
        return try {
            // 假设你使用相同的方式验证，只是密钥或细节可能有所不同
            Jwts.parser().setSigningKey( jwtProperties.adminSecretKey).parseClaimsJws(authorizationToken).body
            true
        } catch (e: Exception) {
            // 处理异常
            false
        }
    }

    /**
     * 通过后台的token获取userId
     */
    fun getUserIdFromAuthorizationToken(token: String): Int? {
        return try {
            val claims = Jwts.parser().setSigningKey( jwtProperties.adminSecretKey).parseClaimsJws(token).body
            claims.subject.toInt()
        } catch (e: Exception) {
            null // 或者处理异常
        }
    }
}

